package com.qiku.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.qiku.base.BaseServlet;
import com.qiku.pojo.Collect;
import com.qiku.pojo.Resource;
import com.qiku.pojo.User;
import com.qiku.service.CollectService;
import com.qiku.service.impl.CollectServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/collect")
public class CollectServlet extends BaseServlet {
    private CollectService collectService = new CollectServiceImpl();
    private  Collect collect = new Collect();

    public void findResourceListByUserId(HttpServletRequest req, HttpServletResponse resp) {
//        System.out.println("findResourceListByUserId:" + "收到请求");
        try {
//        从前端获取用户id
            String user_id = req.getParameter("user_id");
//            System.out.println("user_id:" + user_id);
//        根据id 获取用户收藏的资源列表集合
            List<Resource> resourceList = collectService.findResourceListByUserId(Integer.parseInt(user_id));

            String result = JSON.toJSONString(resourceList);
//            System.out.println("let:" + result);
//            向浏览器响应
            resp.getWriter().println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void addCollect(HttpServletRequest req, HttpServletResponse resp) {
        try {
            HttpSession session = req.getSession();

            User user = (User) session.getAttribute("user");
            String resource_id = req.getParameter("resource_id");
            System.out.println("collect --r_id：" + resource_id);
            if (user != null) {
                int userId = user.getId();
//                System.out.println("user_id：" + userId);
                collect.setResource_id(resource_id);
                collect.setUser_id(userId);
                String msgJSON = collectService.addCollect(collect);
//                System.out.println("插入的返回值：" + msgJSON);
                resp.getWriter().print(msgJSON);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消收藏
     */
    public void subCollect(HttpServletRequest req, HttpServletResponse resp){
        try {
            String resourceId = req.getParameter("resource_id");
            //获取目前登录的用户对象
            User user = (User)req.getSession().getAttribute("user");
            int id = user.getId();
            System.out.println("用户id：" + id);
            //调用service层  subCollect() 方法
            String result = collectService.subCollect(id,resourceId);
            resp.getWriter().println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
